<template>
  <PageLayout full>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>{{ $t('TT.RoomSet.Title') }}</view>
      </HeaderLayout>
    </template>

    <view class="container">
      <PageTitle :title="roomName" :temp="curTemp" :page-hint="powerStatus ? modeText : ''" :show-bar="isShowBarLine" />

      <!-- 开关 -->
      <view class="power-box">
        <view class="power-content">
          <view class="power-img flex-center" :class="{ 'not-active': !powerStatus }" @click="setOff">
            <image v-if="powerStatus" :src="'/pages/appliance/static/TurnOn.png'" mode="widthFix"></image>
            <image v-else :src="'/pages/appliance/static/TurnOn.png'" mode="widthFix"></image>
          </view>
          <view class="tip-popup placement-bottom" v-if="!powerStatus">
            <text>{{ $t('TT.RoomSet.PleaseOnOff.Tips.Text') }}</text>
          </view>
        </view>
      </view>

      <!-- 主要内容 -->
      <view class="roomset-box">
        <view class="mask-alayer" v-if="!powerStatus"></view>
        <view class="tab-box" :class="{ poweroffBg: !powerStatus }">
          <view class="tabs-box">
            <view class="tabs">
              <view class="tab" :class="{ active: curTab === 0 }" @click="chooseTab(0, 2)">
                <view class="tab-text">{{ $t('TT.RoomSet.Tab.RapidMode.Text') }}</view>
                <view class="tabLine"></view>
              </view>
              <view class="tab" :class="{ active: curTab === 1 }" @click="chooseTab(1, 6)">
                <view class="tab-text">{{ $t('TT.RoomSet.Tab.SmartMode.Text') }}</view>
                <view class="tabLine"></view>
              </view>
            </view>
            <view class="rapid-heat-btn" @click="showQuickWarmUpPopView">
              <text>{{ $t('TT.RoomSet.RapidHeat.Lable') }} </text>
              <view class="on-off-style display-flex display-center">
                <text class="white-color">{{
                  rapidHeat ? $t('TT.RoomSet.RapidHeat.On.Text') : $t('TT.RoomSet.RapidHeat.Off.Text')
                }}</text>
                <image class="on-off-styleImage" src="@/pages/appliance/static/TT/img_down.png"></image>
              </view>
            </view>
          </view>
        </view>
        <view class="tab1" :class="{ poweroffBg: !powerStatus }" v-show="curTab === 0">
          <view class="quick-temp bg-color">
            <view class="tem-fav" :class="{ cur: mode === 2 }" @click="chooseManual(2, isMR120 ? onHomeTemp : 20)">{{
              $t('TT.RoomSet.Tab.ManualMode.OnHome.Text')
            }}</view>
            <view class="line-division" :style="mode == 2 || mode == 3 ? 'background-color: transparent;' : ''"></view>
            <view class="tem-fav" :class="{ cur: mode === 3 }" @click="chooseManual(3, isMR120 ? sleepTemp : 18)">{{
              $t('TT.RoomSet.Tab.ManualMode..SleepHome.Text')
            }}</view>
            <view class="line-division" :style="mode == 3 || mode == 4 ? 'background-color: transparent;' : ''"></view>
            <view class="tem-fav" :class="{ cur: mode === 4 }" @click="chooseManual(4, isMR120 ? awayHomeTemp : 8)">{{
              $t('TT.RoomSet.Tab.ManualMode.OnlineHome.Text')
            }}</view>
          </view>
          <ChooseTemp
            isUnit
            :data="powerStatus ? degrees : degreesOff"
            :cur-index="curIndex"
            @chooseTemp="chooseTemp"
            @pickState="changePickState"
          />
        </view>
        <view class="tab1" :class="{ poweroffBg: !powerStatus }" v-show="curTab === 1">
          <view class="quick-temp bg-color">
            <view class="tem-fav" :class="{ cur: mode === 6 }" @click="chooseAutoMode(6)"
              >{{ $t('TT.RoomSet.Tab.OldYoungMode.Text') }}
            </view>
            <view class="tem-fav" :class="{ cur: mode === 7 }" @click="chooseAutoMode(7)">{{
              $t('TT.RoomSet.Tab.CommutersMode.Text')
            }}</view>
          </view>
        </view>
        <!-- 家有老幼 -->
        <view class="tab3" :class="{ hidden: curTab !== 1 || mode !== 6 }">
          <view class="quick-temp">
            <view class="quick-temp-left">
              <view class="quick-temp-box active-box" style="flex: 0.5">{{ $t('TT.RoomSet.EveryDay.Lable') }}</view>
            </view>
            <view class="quick-temp-right"
              >{{ $t('TT.RoomSet.MechineStudy.Lable') }}
              <view @click="showPreheatDesc">
                <image src="@/pages/appliance/static/TT/ic_setting_runningmode.png" class="mode-hint"></image>
              </view>
              <switch color="#108ee9" :checked="preHeat" @change="controlPreheat" />
            </view>
          </view>
        </view>
        <!-- 上班一族 -->
        <view class="tab2" :class="{ hidden: curTab !== 1 || mode !== 7 }">
          <view class="quick-temp">
            <view class="quick-temp-left">
              <view class="quick-temp-out-box">
                <view class="quick-temp-box" :class="{ 'active-box': timeTab == 0 }" @click="switchTimeTab(0)">{{
                  $t('TT.RoomSet.Tab.CommutersMode.OneFive.Text')
                }}</view>
                <view class="quick-temp-box" :class="{ 'active-box': timeTab == 1 }" @click="switchTimeTab(1)">{{
                  $t('TT.RoomSet.Tab.CommutersMode.Weekend.Text')
                }}</view>
              </view>
            </view>
            <view class="quick-temp-right"
              >{{ $t('TT.RoomSet.MechineStudy.Lable')
              }}<view @click="showPreheatDesc">
                <image src="@/pages/appliance/static/TT/ic_setting_runningmode.png" class="mode-hint"></image>
              </view>
              <switch color="#108ee9" :checked="preHeat" @change="controlPreheat" />
            </view>
          </view>
        </view>
      </view>
      <!-- canvas -->
      <view class="container1" v-show="curTab === 1">
        <ec-canvas
          v-if="curTab !== 0"
          id="myChartDomLine"
          canvas-id="mychart-line"
          :echarts="echarts"
          :ec="ecOptions"
        />
      </view>

      <!-- 轻微故障提示 -->
      <TopTips v-model:visible="hasLightErr" :tips-content="errTitle" show-check @check="showErrorDetail"></TopTips>
    </view>

    <template #footer>
      <FooterLayout :size="footerSize" :footer-style="footerStyle">
        <ActionButton :disabled="disabled || !powerStatus" @click="optionConfirm">{{
          $t('TT.RoomSet.Bottom.Button')
        }}</ActionButton>
      </FooterLayout>
    </template>

    <!-- 提示 -->
    <Modal
      v-model:visible="preheatDesc"
      :title="$t('TT.RoomSet.MechineStudy.Dialog.Title')"
      :ok-text="$t('TT.RoomSet.MechineStudy.Dialog.Ok.Button')"
    >
      <view class="tips-text">{{ $t('TT.RoomSet.MechineStudy.Dialog.Content.Text') }}</view>
    </Modal>
    <!-- 房间开关电源提示 -->
    <Modal
      v-model:visible="onOffVisible"
      :title="$t('TT.RoomSet.PowerOff.Dialog.Title')"
      :description="$t('TT.RoomSet.PowerOff.Dialog.Des.Text')"
      :cancel-text="$t('TT.RoomSet.PowerOff.Dialog.Cancel.Text')"
      :ok-text="$t('TT.RoomSet.PowerOff.Dialog.Ok.Text')"
      @ok="onOff"
    >
    </Modal>
    <!-- 应用到所有房间提示框 -->
    <Modal
      v-model:visible="applayAllRoomVisible"
      :title="$t('TT.RoomSet.ApplayAllRoom.Dialog.Title')"
      :description="$t('TT.RoomSet.ApplayAllRoom.Dialog.Des.Text')"
      :cancel-text="$t('TT.RoomSet.ApplayAllRoom.Dialog.Cancel.Text')"
      :ok-text="$t('TT.RoomSet.ApplayAllRoom.Dialog.Ok.Text')"
      @cancel="cancelmManual"
      @ok="confirmManual"
    >
    </Modal>
    <!-- 快速加热模式 -->
    <Drawer :title="$t('TT.RoomSet.RapidHeat.Dialog.Title')" v-model:show="showRapidHeat" alignment="left">
      <view class="rapid-heat">
        <view class="rapid-heat-desc">
          {{ $t('TT.RoomSet.RapidHeat.Dialog.Introduce.Text') }}
        </view>
        <view class="boost-box display-flex display-between">
          <view class="boost-boxTitle">{{ $t('TT.RoomSet.RapidHeat.Switch.Lable') }}</view>
          <switch color="#108ee9" :checked="boostFlag" @change="controlBoost" />
        </view>
        <view class="rapid-heat-box" :class="{ opcityVague: !boostFlag }">
          <view class="rapid-heat-title"
            >{{ $t('TT.RoomSet.RapidHeat.Temp.Lable') }}<text class="unit">（℃）</text></view
          >
          <view class="rapid-heat-ul">
            <view class="process_wrap">
              <view class="spot-box">
                <view class="cur-heat-temp-style" :style="{ left: 2 * progressDistance + 'rpx' }">{{
                  curHeatTemp
                }}</view>
                <view class="line"></view>
                <view class="active_line" :style="{ width: 2 * progressDistance + 'rpx' }"></view>
                <view
                  class="spot"
                  :style="{ left: 2 * progressDistance - 2 + 'rpx' }"
                  @touchmove="moveTo"
                  @touchstart="buttonStart"
                ></view>
              </view>
              <view class="display-flex display-between min-max-box">
                <view class="temp-min">{{ minTemp }}</view>
                <view class="temp-max">{{ maxTemp }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="rapid-heat-box" :class="{ opcityVague: !boostFlag }">
          <view class="rapid-heat-title"
            >{{ $t('TT.RoomSet.RapidHeat.Time.Lable')
            }}<text class="unit">{{ $t('TT.RoomSet.RapidHeat.Time.Unit.Text') }}</text></view
          >
          <view class="rapid-heat-ul">
            <view
              class="rapid-heat-li lager-li"
              :class="{ activeView: curHeatTime == Number(item) }"
              v-for="(item, index) in curHeatTimeList"
              :key="index"
              @click="changeRapidHeat(item)"
            >
              {{ item }}
            </view>
          </view>
        </view>
      </view>
      <template #footer>
        <view class="activation-time-btn display-around">
          <view class="time-btn cancel--btn" @click="showRapidHeat = false">{{
            $t('TT.RoomSet.RapidHeat.Cancle.Button')
          }}</view>
          <view class="time-btn save-btn" @click="confirmRapidHeat">{{ $t('TT.RoomSet.RapidHeat.Ok.Button') }}</view>
        </view>
      </template>
    </Drawer>
    <!-- EMS OTA升级弹框 -->
    <OtaUpgradeIRF :show="isMR100IRFEMS" :mcu-status="mcuStatus"></OtaUpgradeIRF>
    <!-- 轻微故障详情展示 -->
    <Modal
      :visible="showLightErr"
      :title="errTitle"
      :ok-text="$t('TT.Detail.Error.Dialog.Ok.Text')"
      @ok="showLightErr = false"
    >
      <view class="modal-sub-tile">({{ $t('TT.Detail.Error.SubTitle.Text') }}{{ errCode }})</view>
      <view class="modal-serve no-bottom">
        <text class="modal-content">{{ $t('TT.Detail.Error.Dialog.Tips.Lable.Text') }}</text>
        <text class="light-err-solve-view">{{ serviceRemind }}</text>
      </view>
    </Modal>
  </PageLayout>
</template>

<script lang="ts">
export type SettingsSubmitType = {
  settings: { key: string; value: string | number }[]
}
</script>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import FooterLayout from '@/layout/page/footer.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'
import PageTitle from '../components/pageTitle/pageTitle.vue'
import ChooseTemp from '../components/chooseTemp/chooseTemp.vue'
import Modal from '@/common/modal.vue'
import Drawer from '@/common/drawer.vue'
import OtaUpgradeIRF from '../otaUpgrade/otaUpgradeIRF.vue'
import TopTips from '@/common/topTips.vue'

import { footerStyle, footerSize } from '@/layout/appliance/style'
import type { TTController } from '@/controller/TT/definition'
import { actionDebounce, showLoading, useEventReceiver } from '@/utils/mpHelper'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { useTTErrorCode, type RoomListType } from '../TTHelper'
import {
  getTTRoomDetail,
  setTTSetting,
  type TTRoomDetailType,
  getBLTTSpecialSetting,
  type BLTTSettingValueType,
} from '@/api/tt'
import {
  getRoomPreheat,
  getTTAutoMode,
  getTTRoomMode,
  getTTRoomTmMode,
  getTTSummerMode,
  setRoomPreheat,
  setTTProgramDay,
  setTTProgramMode,
  setTTRoomMode,
  TT_SETTING_BlState,
  TT_STATUS_MCUSTATUS,
} from '../SmartAssistantTool'
import type { WS } from '@/utils/socket/types'
import { TT_SUMMER_BLMODE } from '@/constants/Command'
import { useRoomDayData } from '../chartData/chartData'
import type { EcCanvasOptions, EcCanvasComponent } from '@/pages/appliance/TT/ec-canvas/ec-canvas'
import type { Remote } from '@/controller/base/types/remote'
import { useEnvStore } from '@/store/env'
import { getEcharts } from '../useEcharts'
import { Room_Err } from '../TTErrorCode'

const echarts = getEcharts()

const headerStyle = {
  backgroundColor: '#fff',
}
const degrees = ref<{ value: number }[]>([])
const degreesOff = ref<{ value: string }[]>([])
for (let i = 5; i <= 35; i += 0.5) {
  degrees.value.push({
    value: i,
  })
  degreesOff.value.push({
    value: '- -',
  })
}
const MODES = new Map([
  [0, '自动'],
  [128, '自动'],
  [2, '在家'],
  [3, '睡眠'],
  [4, '离家'],
])
const PACKAGE_ARRAY = [0, 6, 12, 19]

const control = ref<TTController.Control | null>(null)
let roomDayControl: ReturnType<typeof useRoomDayData> | null = null
const tempLineData = ref<[number, number][]>([])
const dataV = ref<{ value: number[] }[]>([])
useEventReceiver('control', (received: TTController.Control) => {
  control.value = received
  listenMessages()
  roomDayControl = useRoomDayData({ tempLineData, dataV })
})

const ecOptions: EcCanvasOptions = {
  lazyLoad: true,
}

const haId = ref('')
const isMR120 = computed(() => haId.value.indexOf('MR120') !== -1)
const isMR100IRFEMS = computed(() => haId.value.split('-')[1] === 'MR100iRF10720EMS')
const isShowBarLine = computed(
  () =>
    ([3276.7, 409.5].includes(Number(curTemp.value)) && isMR120.value) ||
    (Number(curTemp.value) == 120 && isMR100IRFEMS.value)
)
const settings = ref<TTRoomDetailType[]>([])

const disabled = ref(false)
const roomName = ref('')
const roomIndex = ref(0)
const roomKey = ref('')
const roomId = ref('0')
const curTemp = ref('--')
const setTemp = ref('--')
const powerStatus = ref(true)
const modeText = ref('') //当前模式
const roomList = ref<RoomListType[]>([])
const curTab = ref(0)
const rapidHeat = ref(false)
const language = ref('zh')
const mode = ref(0)
const tempMode = ref(0)
const curIndex = ref(0)
const tempIndex = ref(0)
const pickState = ref(false)
const preHeat = ref(false)
const timeTab = ref(0)
const curHeatTemp = ref(18)
const curHeatTime = ref(1)
const curHeatTimeList = ref(['1', '1.5', '2', '2.5', '3'])
const maxTemp = ref(30)
const minTemp = ref(18)
const progressDistance = ref(0)
const buttonLeft = ref(0)

const sleepTemp = ref(0)
const awayHomeTemp = ref(0)
const onHomeTemp = ref(0)

const roomConfig = ref('')
const roomState = ref(0)

const summerMode = ref(false)
const manualMode = ref(false)

const showRoomDialog = ref(false)
const preheatDesc = ref(false)

const showRapidHeat = ref(false)
const boostFlag = ref(false)

const mcuStatus = ref(0)

watch(
  () => isMR100IRFEMS.value,
  (value) => {
    if (value) {
      minTemp.value = 25
      maxTemp.value = 30
      curHeatTemp.value = 25
      curHeatTimeList.value = ['1', ' 2', '3']
    }
  }
)

const { hasLightErr, showLightErr, errTitle, errCode, serviceRemind, getErrDetail } = useTTErrorCode(
  settings,
  { isMR120, isMR100IRFEMS, roomId },
  control.value as TTController.Control
)

onLoad((query: any) => {
  haId.value = query?.haId
  roomName.value = decodeURIComponent(query?.name)
  roomIndex.value = query?.curIndex ? parseInt(query?.curIndex) : 0
  roomList.value = JSON.parse(decodeURIComponent(query?.roomList))
  roomKey.value = roomList.value[roomIndex.value].key
  roomId.value = roomKey.value.replace('Rm', '')
  getTTRoomDetailFun()
  watchEffect(() => {
    settings.value = control.value?.store._datasource.settings as TTRoomDetailType[]
  })
})

onUnload(() => {
  control.value?.remote.removeBatchObserves(observes)
})

/**
 * 加载房间详情数据接口
 */
async function getTTRoomDetailFun() {
  const res = await getTTRoomDetail(haId.value, roomId.value)
  let roomDetail = res.data['room' + roomId.value]
  initInfo(roomDetail)
}
/**
 * 初始化详情数据
 * @param list
 */
function initInfo(list: TTRoomDetailType[]) {
  if (!list || list.length === 0) return
  list.forEach((item, index) => {
    switch (item.key) {
      case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Set':
        let newIndex = degrees.value.findIndex((degree: { value: number }) => degree.value === Number(item.value) / 10)
        curIndex.value = newIndex
        tempIndex.value = newIndex
        setTemp.value = Number(item.value) / 10 + ''
        break
      case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Mode':
        let newCurTab = 0
        let newMode = 0
        if (Number(item.value) == 2 || Number(item.value) == 3 || Number(item.value) == 4 || Number(item.value) == 5) {
          newCurTab = 0
          newMode = Number(item.value)
        } else {
          newCurTab = 1
          if (Number(item.value) == 0) {
            newMode = 6
          } else {
            newMode = 7
          }
        }
        curTab.value = newCurTab
        mode.value = newMode
        modeText.value = MODES.get(Number(item.value)) || '自动'
        powerStatus.value = !(Number(item.value) === 5)
        if (curTab.value !== 0 && isMR120.value) getRoomDayData()
        break
      case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Temp':
        curTemp.value = Number(item.value) / 10 + ''
        break
      case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Preheat':
        preHeat.value = Number(item.value) !== 0
        break
      case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost':
        let formatBoost = parseInt(item.value as string).toString(16)

        for (let i = 0; i < 2 - formatBoost.length; i++) {
          formatBoost = '0' + formatBoost
        }
        let isbool = !(parseInt(item.value as string) === 0)
        let newCurHeatTemp = isMR120 ? 18 : 25
        let newCurHeatTime = 1
        if (isbool) {
          if (isMR120.value) {
            newCurHeatTemp = parseInt(formatBoost.substr(0, 1), 16) + 18
            newCurHeatTime = parseInt(formatBoost.substr(1, 1), 16) / 2
          } else {
            newCurHeatTemp = 24 + Number(formatBoost.substr(0, 1))
            newCurHeatTime = Number(formatBoost.substr(1, 1))
          }
        }
        rapidHeat.value = isbool
        curHeatTemp.value = newCurHeatTemp
        curHeatTime.value = newCurHeatTime
        let distand = (Number(newCurHeatTemp) - (isMR120.value ? 18 : 25)) * (310 / (maxTemp.value - minTemp.value))
        progressDistance.value = distand > 0 ? distand : 0
        buttonLeft.value = distand > 0 ? distand : 0
        break
      case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'SetStorage':
        let value = Number(item.value).toString(16)
        let needZeroPaddingLength = 8 - value.length
        for (let i = 0; i < needZeroPaddingLength; i++) {
          value = '0' + value
        }
        sleepTemp.value = parseInt(value.substring(value.length - 2, value.length), 16) / 2
        awayHomeTemp.value = parseInt(value.substring(value.length - 4, value.length - 2), 16) / 2
        onHomeTemp.value = parseInt(value.substring(value.length - 6, value.length - 4), 16) / 2
        break
      case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config':
        roomConfig.value = item.value as string
        let newModeConfig = getTTRoomMode(item.value as string)
        mode.value = newModeConfig
        tempMode.value = newModeConfig
        modeText.value = MODES.get(newModeConfig) || '自动'
        powerStatus.value = !(Number(newModeConfig) === 5)
        if (newModeConfig === 0) {
          let tmMode = getTTRoomTmMode(item.value as string)
          curTab.value = 1
          mode.value = tmMode === 0 ? 6 : 7
          getRoomDayData(1, item.value as number)
        }
        break
      case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State':
        roomState.value = Number(item.value)
        let newPreHeat = getRoomPreheat(item.value as string)
        preHeat.value = newPreHeat ? true : false
        break
      case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'ErrCode':
        if (Number(item.value) !== 0) {
          getErrDetail(Room_Err, item.value + '', item.param)
        } else {
          hideErrPop()
        }
        break
      case TT_STATUS_MCUSTATUS:
        mcuStatus.value = item.value as number
        break
      case TT_SETTING_BlState:
        if (getTTSummerMode(item.value as string) === 1) {
          summerMode.value = true
        }
        if (getTTAutoMode(item.value as string) === 1) {
          manualMode.value = true
        }
        break
      default:
        break
    }
  })
}
/**
 * 切换tab
 */
function chooseTab(tabIndex: number, modeIndex: number) {
  if (curTab.value === tabIndex) return
  mode.value = modeIndex
  roomDayControl?.destroyChart()
  if (tabIndex === 0) {
    let temp = 0
    if (isMR120.value) {
      temp = onHomeTemp.value
    } else {
      temp = 20
    }
    let mateIndex = degrees.value.findIndex((item) => item.value === temp)
    nextTick(() => {
      curIndex.value = mateIndex
      tempIndex.value = mateIndex
    })
  } else {
    if (isMR120.value) {
      getRoomDayData()
    } else {
      getRoomDayData(1, 20)
    }
  }
  curTab.value = tabIndex
}
/**
 * 切换快速模式tab
 */
function chooseManual(modeIndex: number, temp: number) {
  if (mode.value === modeIndex || pickState.value) return
  mode.value = modeIndex
  if (modeIndex === tempMode.value) temp = Number(setTemp.value)
  let mateIndex = degrees.value.findIndex((item) => item.value === temp)
  curIndex.value = mateIndex
  tempIndex.value = mateIndex
}
/**
 * 选择温度
 * @param index
 */
function chooseTemp(index: number) {
  curIndex.value = index
  tempIndex.value = index
}
/**
 * 滚动
 * @param state
 */
function changePickState(state: boolean) {
  pickState.value = state
}
/**
 * 确定
 */
const applayAllRoomVisible = ref(false)
const optionConfirm = actionDebounce({
  call: async () => {
    if (roomKey.value == 'Rm0' && roomList.value.length > 1) {
      applayAllRoomVisible.value = true
    } else {
      optionConfirmManual(false, 0)
    }
  },
})
/**
 * 取消应用所有房间
 */
function cancelmManual() {
  showRoomDialog.value = false
  optionConfirmManual(false, 0)
}
/**
 * 确定应用所有房间
 */
function confirmManual() {
  showRoomDialog.value = false
  optionConfirmManual(true, 0)
}
/**
 * 区分模式下发命令
 */
const optionConfirmManual = actionDebounce({
  call: async (allroom: boolean, count: number) => {
    if (curTab.value === 0) {
      setManual(allroom, 0)
    } else {
      let data = roomDayControl?.lineData.value ? roomDayControl?.lineData.value : [{ value: [0, 0] }]
      let params: SettingsSubmitType = {
        settings: [],
      }
      let modeId = timeTab.value == 0 ? 1 : 2
      if (!allroom) {
        if (isMR120.value) {
          if (mode.value == 6) {
            params = {
              settings: [
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx1',
                  value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx2',
                  value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx3',
                  value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx4',
                  value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx1',
                  value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx2',
                  value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx3',
                  value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx4',
                  value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Mode',
                  value: 0,
                },
              ],
            }
          } else {
            params = {
              settings: [
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx1',
                  value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx2',
                  value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx3',
                  value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx4',
                  value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Mode',
                  value: 128,
                },
              ],
            }
          }
        } else {
          let newRoomConfig1 = setTTProgramMode(roomConfig.value, 0)
          newRoomConfig1 = setTTProgramMode(
            roomConfig.value,
            mode.value === 7 ? parseInt('0x24', 16) : parseInt('0x14', 16)
          )
          params = {
            settings: [
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx1',
                value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx2',
                value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx3',
                value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx4',
                value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State',
                value: setTTProgramDay(roomState.value + '', timeTab.value === 0 ? 1 : 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
                value: newRoomConfig1,
              },
            ],
          }
        }
      } else {
        // 应用到所有房间
        let max = roomList.value.length
        if (max > PACKAGE_ARRAY[count + 1]) {
          max = PACKAGE_ARRAY[count + 1]
        }
        for (let i = PACKAGE_ARRAY[count]; i < max; i++) {
          if (isMR120) {
            if (mode.value == 6) {
              params.settings.push(
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm1Dx1',
                  value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm1Dx2',
                  value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm1Dx3',
                  value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm1Dx4',
                  value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm2Dx1',
                  value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm2Dx2',
                  value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm2Dx3',
                  value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm2Dx4',
                  value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Mode',
                  value: 0,
                }
              )
            } else {
              params.settings.push(
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm' + modeId + 'Dx1',
                  value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm' + modeId + 'Dx2',
                  value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm' + modeId + 'Dx3',
                  value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Tm' + modeId + 'Dx4',
                  value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
                },
                {
                  key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Mode',
                  value: 128,
                }
              )
            }
          } else {
            let newRoomConfig2 = setTTProgramMode(roomConfig.value, 0)
            newRoomConfig2 = setTTProgramMode(
              roomConfig.value,
              mode.value === 7 ? parseInt('0x24', 16) : parseInt('0x14', 16)
            )
            params.settings.push(
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'TmDx1',
                value: formatTmDx(data[1].value[0], 0, data[1].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'TmDx2',
                value: formatTmDx(data[2].value[0], 0, data[2].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'TmDx3',
                value: formatTmDx(data[3].value[0], 0, data[3].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'TmDx4',
                value: formatTmDx(data[4].value[0], 0, data[4].value[1] * 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'State',
                value: setTTProgramDay(roomState.value + '', timeTab.value === 0 ? 1 : 2),
              },
              {
                key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Config',
                value: newRoomConfig2,
              }
            )
          }
        }
      }
      const res = await setTTSetting(haId.value, params)
      if (res.code == 0) {
        if (allroom && PACKAGE_ARRAY[count + 1] < roomList.value.length) {
          optionConfirmManual(allroom, count + 1)
        } else {
          uni.showToast({
            title: '设置成功',
            icon: 'none',
          })
        }
      }
    }
  },
})
/**
 * 格式化tmdx数据,先将每个转成十六进制合并，再转十进制
 */
function formatTmDx(hour: number, miu: number, temp: number) {
  let concatData = 0
  if (isMR120.value) {
    let hourminute = Number((hour * 60 + miu) / 30)
    let concatText = fixNum0(temp.toString(16)) + fixNum0(hourminute.toString(16))
    concatData = parseInt(concatText, 16)
  } else {
    let hourminute = hour * 10 + miu
    let concatText = fixNum0(hourminute.toString(16)) + fixNum0(temp.toString(16))
    console.log(concatText, 'concatText')
    concatData = parseInt(concatText, 16)
  }
  return concatData
}
// 补0
function fixNum0(num: string) {
  return num.length < 2 ? '0' + num : num
}
/**
 * 快速模式设置
 */
async function setManual(allroom: boolean, count: number) {
  let params: SettingsSubmitType = {
    settings: [],
  }
  if (!allroom) {
    if (isMR120.value) {
      params = {
        settings: [
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Set',
            value: degrees.value[tempIndex.value].value * 10,
          },
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Mode',
            value: mode.value,
          },
        ],
      }
    } else {
      params = {
        settings: [
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Set',
            value: degrees.value[tempIndex.value].value * 10,
          },
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
            value: setTTRoomMode(roomConfig.value, mode.value + ''),
          },
        ],
      }
    }
  } else {
    params = {
      settings: [],
    }
    let max = roomList.value.length
    if (max > PACKAGE_ARRAY[count + 1]) {
      max = PACKAGE_ARRAY[count + 1]
    }
    for (let i = PACKAGE_ARRAY[count]; i < max; i++) {
      if (isMR120) {
        params.settings.push(
          {
            key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Set',
            value: degrees.value[tempIndex.value].value * 10,
          },
          {
            key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Mode',
            value: mode.value,
          }
        )
      } else {
        params.settings.push(
          {
            key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Set',
            value: degrees.value[tempIndex.value].value * 10,
          },
          {
            key: 'SmartAssistant.TT.Setting.' + roomList.value[i].key + 'Config',
            value: setTTRoomMode(roomConfig.value, mode.value + ''),
          }
        )
      }
    }
  }
  await setSetting(params, allroom, 0)
}
/**
 * 下发设置指令
 * @param params
 */
async function setSetting(params: {}, allroom?: boolean, count?: number) {
  const res = await setTTSetting(haId.value, params)
  if (res.code === 0) {
    if (allroom && count && PACKAGE_ARRAY[count + 1] < roomList.value.length) {
      setManual(allroom, count + 1)
    } else {
      uni.showToast({
        title: '设置成功',
        icon: 'none',
      })
    }
  }
}
/**
 * 切换智能模式
 */
function chooseAutoMode(modeIndex: number) {
  if (mode.value === modeIndex) return
  mode.value = modeIndex
  timeTab.value = 0
  roomDayControl?.destroyChart()
  if (isMR120.value) {
    getRoomDayData()
  } else {
    if (modeIndex == 6) {
      getRoomDayData(1, 20)
    } else if (modeIndex == 7) {
      getRoomDayData(1, 36)
    }
  }
}
/**
 * 点击开关机
 */
const onOffVisible = ref(false)
const setOff = actionDebounce({
  call: async () => {
    if (powerStatus.value) {
      onOffVisible.value = true
    } else {
      onOff()
    }
  },
})
/**
 * 下发开关机指令
 */
function onOff() {
  let params = {}
  if (isMR120.value) {
    params = {
      settings: [
        {
          key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Mode',
          value: powerStatus.value ? 5 : 2,
        },
      ],
    }
  } else if (isMR100IRFEMS.value) {
    params = {
      settings: [
        {
          key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
          value: setTTRoomMode(roomConfig.value, powerStatus.value ? '5' : '2'),
        },
      ],
    }
  }
  showLoading(async () => {
    await setSetting(params)
  })
}

/**
 * 显示机器学习描述
 */
function showPreheatDesc() {
  preheatDesc.value = true
}
/**
 * 控制机器自学习
 */
const controlPreheat = actionDebounce({
  call: async () => {
    let params = {}
    if (isMR120.value) {
      params = {
        settings: [
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Preheat',
            value: preHeat.value ? 0 : 1,
          },
        ],
      }
    } else {
      params = {
        settings: [
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State',
            value: setRoomPreheat(roomState.value + '', preHeat.value ? '0' : '1'),
          },
        ],
      }
    }
    await setSetting(params)
  },
})
/**
 * 切换周六周日
 */
function switchTimeTab(curTimeIdx: number) {
  if (curTimeIdx === timeTab.value) return
  timeTab.value = curTimeIdx
  roomDayControl?.destroyChart()
  if (curTimeIdx == 0) {
    if (isMR120.value) {
      getRoomDayData()
    } else {
      getRoomDayData(1, 36)
    }
  } else {
    if (isMR120.value) {
      getRoomDayData()
    } else {
      getRoomDayData(2, 36)
    }
  }
}
/**
 * 加开快速加热弹框
 */
function showQuickWarmUpPopView() {
  showRapidHeat.value = true
  boostFlag.value = rapidHeat.value
}
/**
 * 获取房间编程数据
 */
function getRoomDayData(day?: number, tmMode?: number) {
  showLoading(async () => {
    let postData = {}
    let modeId = 0
    if (isMR120.value) {
      if (mode.value == 6) {
        modeId = 1
      } else {
        if (timeTab.value == 0) {
          modeId = 1
        } else {
          modeId = 2
        }
      }
      postData = {
        data: {
          data: [
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx1',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx2',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx3',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx4',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Mode',
              value: mode.value == 6 ? 0 : 128,
            },
          ],
        },
      }
    } else {
      postData = {
        data: {
          data: [
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx1',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx2',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx3',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx4',
              value: 0,
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State',
              value: setTTProgramDay(roomState.value + '', day as number),
            },
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
              value: setTTProgramMode(roomConfig.value, tmMode as number),
            },
          ],
        },
      }
    }
    const res = await getBLTTSpecialSetting(haId.value, postData)
    if (res.code === 0) {
      tempLineData.value = []
      const { blSettings } = res.data
      let sourceData = []
      let sourceDict: Record<string, BLTTSettingValueType> = {}
      if (isMR120.value) {
        for (let i = 0; i < blSettings.length; i++) {
          if (blSettings[i].key.indexOf('SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx') != -1) {
            let key = blSettings[i].key.replace(
              'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm' + modeId + 'Dx',
              ''
            )
            sourceDict[key.toString()] = blSettings[i]
          }
        }
        let formatDict = Object.keys(sourceDict).sort()
        for (var key in formatDict) {
          sourceData.push(sourceDict[formatDict[key]])
        }
        sourceData.forEach((e) => {
          let curData = Number(e.value).toString(16)
          let needZeroPaddingLength = 4 - curData.length
          for (var i = 0; i < needZeroPaddingLength; i++) {
            curData = '0' + curData
          }
          let temp = parseInt(curData.substring(0, 2), 16) / 2
          let hourminute = parseInt(curData.substring(2, 4), 16)
          let hour = (Number(hourminute) * 30) / 60
          tempLineData.value.push([hour, temp])
        })
      } else {
        for (let i = 0; i < blSettings.length; i++) {
          if (blSettings[i].key.indexOf('SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx') != -1) {
            let key = blSettings[i].key.replace('SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx', '')
            sourceDict[key] = blSettings[i]
          }
        }
        let formatDict = Object.keys(sourceDict).sort()
        for (var key in formatDict) {
          sourceData.push(sourceDict[formatDict[key]])
        }
        sourceData.forEach((e) => {
          let curData = Number(e.value).toString(16)
          while (curData.length < 5) {
            curData = 0 + curData
          }
          let temp = parseInt(curData.substring(3, 5), 16) / 2
          let hourminute = parseInt(curData.substring(0, 3), 16)
          let hour = (hourminute - (hourminute % 10)) / 10
          tempLineData.value.push([hour, temp])
        })
      }
      dataV.value = [
        {
          value: [-5, 0],
        },
      ]
      for (let i = 0; i < tempLineData.value.length; i++) {
        let value = {
          value: [tempLineData.value[i][0], 0],
        }
        dataV.value.push(value)
      }
      dataV.value.push({
        value: [30, 0],
      })
      roomDayControl?.initData()
      initChart()
      uni.hideLoading()
    }
  })
}
/**
 * 快速加热弹框开关
 */
function controlBoost() {
  boostFlag.value = !boostFlag.value
}
/**
 * 滑块开始移动
 */
const startPoint = ref()
function buttonStart(e: TouchEvent) {
  if (!boostFlag.value) return
  startPoint.value = e.touches[0]
}
/**
 * 设置滑块移动距离和滑动温度
 */
function moveTo(e: TouchEvent) {
  if (!boostFlag.value) return
  let maxDistance = 310
  let endPoint = e.touches[e.touches.length - 1]
  let translateX = endPoint.clientX - startPoint.value.clientX
  startPoint.value = endPoint
  let newButtonLeft = buttonLeft.value + translateX
  // 显示滑块最远距离
  if (newButtonLeft > maxDistance) {
    newButtonLeft = maxDistance
  }
  // 限制滑动最近距离
  if (newButtonLeft < 0) {
    newButtonLeft = 0
  }
  progressDistance.value = newButtonLeft
  buttonLeft.value = newButtonLeft
  curHeatTemp.value = parseInt(newButtonLeft / (maxDistance / (maxTemp.value - minTemp.value)) + minTemp.value + '')
}
/**
 * 修改快速加热温度或者时间
 */
function changeRapidHeat(value: string) {
  if (!boostFlag.value) return
  curHeatTime.value = Number(value)
}
/**
 * 确定快速加热发送命令
 */
const confirmRapidHeat = actionDebounce({
  call: async () => {
    let params = {}
    if (boostFlag.value) {
      let rapidHeatData = ''
      if (isMR120.value) {
        rapidHeatData = (curHeatTemp.value - 18).toString(16) + (curHeatTime.value * 2).toString(16)
        params = {
          settings: [
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost',
              value: parseInt(rapidHeatData, 16),
            },
          ],
        }
      } else {
        rapidHeatData = '0x' + (curHeatTemp.value - 24) + curHeatTime.value
        params = {
          settings: [
            {
              key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost',
              value: parseInt(rapidHeatData, 16),
            },
          ],
        }
      }
    } else {
      params = {
        settings: [
          {
            key: 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost',
            value: 0,
          },
        ],
      }
    }
    await setSetting(params)
    showRapidHeat.value = false
  },
})

const messages = ref<WS.MessageItem[]>([])
let tmdxChangeSocketTimestamp = 0
/**
 * 监听
 */
const observeSettingKeys = computed(() => [
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Set',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Mode',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Temp',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Preheat',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'SetStorage',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'ErrCode',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx1',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx2',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx3',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx4',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx1',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx2',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx3',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx4',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx1',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx2',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx3',
  'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx4',
  TT_SUMMER_BLMODE,
  TT_SETTING_BlState,
  TT_STATUS_MCUSTATUS,
])
const observes: Remote.BatchObserve<TTController.Store>[] = [
  {
    matcher: (msg) => observeSettingKeys.value.includes(msg.key),
    handler: (msg, remote, msgContext) => handleMsg(msg, msgContext?.timestamp || 0),
  },
]
function listenMessages() {
  control.value?.remote.addBatchObserves(observes)
}
/**
 * 监听信息
 * @param item
 * @returns
 */
function handleMsg(item: WS.MessageItem, timestamp: number) {
  console.error('handleMsg', item)
  if (!item) {
    return
  }
  switch (item.key) {
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Set':
      let newIndex = degrees.value.findIndex((degree: { value: number }) => degree.value === Number(item.value) / 10)
      curIndex.value = newIndex
      tempIndex.value = newIndex
      setTemp.value = Number(item.value) / 10 + ''
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Mode':
      let newCurTab = 0
      let newMode = 0
      if (Number(item.value) == 2 || Number(item.value) == 3 || Number(item.value) == 4 || Number(item.value) == 5) {
        newCurTab = 0
        newMode = Number(item.value)
      } else {
        newCurTab = 1
        if (Number(item.value) == 0) {
          newMode = 6
        } else {
          newMode = 7
        }
      }
      curTab.value = newCurTab
      mode.value = newMode
      modeText.value = MODES.get(Number(item.value)) || '自动'
      powerStatus.value = !(Number(item.value) === 5)
      if (curTab.value !== 0 && isMR120.value) {
        if (Math.abs(tmdxChangeSocketTimestamp - timestamp) > 1000) {
          tmdxChangeSocketTimestamp = timestamp
          getRoomDayData()
        }
      }

      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Temp':
      curTemp.value = Number(item.value) / 10 + ''
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Preheat':
      preHeat.value = Number(item.value) !== 0
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Boost':
      let formatBoost = parseInt(item.value as string).toString(16)

      for (let i = 0; i < 2 - formatBoost.length; i++) {
        formatBoost = '0' + formatBoost
      }
      let isbool = !(parseInt(item.value as string) === 0)
      let newCurHeatTemp = isMR120 ? 18 : 25
      let newCurHeatTime = 1
      rapidHeat.value = isbool
      boostFlag.value = isbool
      if (isbool) {
        if (isMR120.value) {
          newCurHeatTemp = parseInt(formatBoost.substr(0, 1), 16) + 18
          newCurHeatTime = parseInt(formatBoost.substr(1, 1), 16) / 2
        } else {
          newCurHeatTemp = 24 + Number(formatBoost.substr(0, 1))
          newCurHeatTime = Number(formatBoost.substr(1, 1))
        }

        curHeatTemp.value = newCurHeatTemp
        curHeatTime.value = newCurHeatTime
        let distance = (Number(newCurHeatTemp) - (isMR120.value ? 18 : 25)) * (310 / (maxTemp.value - minTemp.value))
        progressDistance.value = distance > 0 ? distance : 0
        buttonLeft.value = distance > 0 ? distance : 0
      } else {
        curHeatTemp.value = isMR120.value ? 18 : 25
        curHeatTime.value = 1
        progressDistance.value = 0
        buttonLeft.value = 0
      }
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'SetStorage':
      let value = Number(item.value).toString(16)
      let needZeroPaddingLength = 8 - value.length
      for (let i = 0; i < needZeroPaddingLength; i++) {
        value = '0' + value
      }
      sleepTemp.value = parseInt(value.substring(value.length - 2, value.length), 16) / 2
      awayHomeTemp.value = parseInt(value.substring(value.length - 4, value.length - 2), 16) / 2
      onHomeTemp.value = parseInt(value.substring(value.length - 6, value.length - 4), 16) / 2
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'State':
      roomState.value = Number(item.value)
      let newPreHeat = getRoomPreheat(item.value as string)
      preHeat.value = newPreHeat ? true : false
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Config':
      roomConfig.value = item.value as string
      let newModeConfig = getTTRoomMode(item.value as string)
      let newTmMode = getTTRoomTmMode(item.value as string)
      let curTabs = 0
      if (newModeConfig == 0) {
        curTabs = 1
        if (newTmMode == 0) {
          newModeConfig = 6
        } else {
          newModeConfig = 7
        }
      }
      mode.value = newModeConfig
      tempMode.value = newModeConfig
      modeText.value = MODES.get(newModeConfig === 6 || newModeConfig === 7 ? 0 : newModeConfig) || '自动'
      powerStatus.value = !(newModeConfig === 5)
      curTab.value = curTabs
      if (curTabs === 1) {
        if (Math.abs(tmdxChangeSocketTimestamp - timestamp) > 1000) {
          tmdxChangeSocketTimestamp = timestamp
          if (mode.value === 6) {
            getRoomDayData(1, 20)
          } else {
            if (timeTab.value == 0) {
              getRoomDayData(1, 36)
            } else {
              getRoomDayData(2, 36)
            }
          }
        }
      }
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'ErrCode':
      if (Number(item.value) != 0) {
        getErrDetail(Room_Err, item.value + '', item.param as string)
      } else {
        hideErrPop()
      }
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx1':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx2':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx3':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm1Dx4':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx1':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx2':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx3':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'Tm2Dx4':
      if (Math.abs(tmdxChangeSocketTimestamp - timestamp) > 1000) {
        tmdxChangeSocketTimestamp = timestamp
        if (curTab.value == 1) {
          getRoomDayData()
        }
      }
      break
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx1':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx2':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx3':
    case 'SmartAssistant.TT.Setting.Rm' + roomId.value + 'TmDx4':
      if (Math.abs(tmdxChangeSocketTimestamp - timestamp) > 1000) {
        tmdxChangeSocketTimestamp = timestamp
        if (curTab.value == 1) {
          if (mode.value == 6) {
            getRoomDayData(1, 20)
          } else {
            if (timeTab.value == 0) {
              getRoomDayData(1, 36)
            } else {
              getRoomDayData(2, 36)
            }
          }
        }
      }
      break
    case TT_SUMMER_BLMODE:
      let summerMode = Number(item.value) == 1
      if (summerMode) {
        onBack()
      }
      break
    case TT_SETTING_BlState:
      if (getTTSummerMode(item.value as string) == 1) {
        onBack()
      }
      break
    case TT_STATUS_MCUSTATUS:
      mcuStatus.value = item.value as number
      break
    default:
      break
  }
}
/**
 * 返回上一页
 */
function onBack() {
  uni.navigateBack()
}

const instance = getCurrentInstance()
const envStore = useEnvStore()
let ecComponent: EcCanvasComponent | null = null
// 点击按钮后初始化图表
function initChart() {
  ecComponent = (instance as any).ctx.selectComponent('#myChartDomLine') as EcCanvasComponent | null
  if (!ecComponent) {
    return uni.hideLoading()
  }

  ecComponent.init((canvas, width, height) => {
    /*
     * 获取组件的 canvas、width、height 后的回调函数
     * 在这里初始化图表
     */
    const chart = echarts.init(canvas, void 0, {
      width,
      height,
      devicePixelRatio: envStore.systemInfo.pixelRatio,
    })
    roomDayControl?.setChartInstance(chart)
    roomDayControl?.setOption()
    // wx.hideLoading()

    // 注意这里一定要返回 chart 实例，否则会影响事件处理等
    return chart
  })
}

/**
 * 隐藏错误弹框
 */
function hideErrPop() {
  hasLightErr.value = false
  showLightErr.value = false
}

/**
 * 展示轻微报错详情
 */
function showErrorDetail() {
  showLightErr.value = true
}
</script>

<style scoped lang="less">
@import '@/styles/common.less';
@import '@/styles/switch.less';
@import '../style/room.less';
@import '../style/TT.less';
</style>
